package com.geekaca.web.servlet;

import com.geekaca.web.mapper.UserMapper;
import com.geekaca.web.pojo.User;
import com.geekaca.web.utils.SqlUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(urlPatterns = "/searchByUsername")
public class SearchServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setHeader("Content-type", "text/html; charset=utf-8");
        PrintWriter writer = resp.getWriter();
        String uname = req.getParameter("user_name");

        if ("".equals(uname.trim())) {
            writer.write("输入不能为空");
            resp.sendRedirect(req.getContextPath() + "/search.html");
            return;
        }
        SqlSession sqlSession = SqlUtil.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        List<User> users = userMapper.selectUserByName(uname);

        if (users.size() == 0) {
            writer.write("没有找到用户名中含有： " + uname + " 用户");
            return;
        }

        for (int i = 0; i < users.size(); i++) {
            User user = users.get(i);
            writer.write("用户名： " + user.getUsername());
            writer.write("<br>性别： " + (user.getGender() == 1 ? "男" : "女"));
            writer.write("<br>城市： " + user.getUsername());
            writer.write("<br>用户名： " + user.getCity());
            writer.write("<br>简介： " + user.getDesc());
            writer.write("<hr/>");
        }


    }
}
